// pages/groups/room/zk/zk.js
import { Base64 } from '../../../../utils/base64';
import {httpBaseUrl} from '../../../../utils/config'
import { long2Bytes, Uint8Array2HexStr } from '../../../../utils/util';
const groups =  [
    { text: '5', value: 1 },
    { text: '10', value: 2},
    { text: '15', value: 3, type: 'warn' },
    { text: '20', value: 4 },
    { text: '30', value: 5 },
    { text: '40', value: 6 },
    { text: '50', value: 7 },
    { text: '60', value: 8 },
    { text: '70', value: 9 },
    { text: '80', value: 10 },
    { text: '90', value: 11 },
    { text: '120', value: 12 },
    { text: '永久', value: 13 },
]
const groupsMap = groupsMap ?? groups.reduce((a, b) => Object.assign(a, {[b.value]: b.text}), {});

const lampsList =  [
    { name: '加密', value: 1 },
    { name: '不加密', value: 0}
]

const formData = {
    available: 3,
    lamps: 1
};
let tempFilePath = ""
const flags = new Uint8Array([232, 233]);
Page({

    /**
     * 页面的初始数据
     */
    data: {
        groups,
        groupsMap,
        formData,
        groupsText: groupsMap[formData.available],
        showActionsheet: !1,
        lampsList
    },

    tapRecord: function (params) {
        wx.navigateTo({
          url: '/pages/index/record/record',
        })
    },

    /**生成临时密码 */
    async tapGenerate() {
        
        const {formData} = this.data;
        const {placeId, pname} = wx.getStorageSync('place');
        tempFilePath = `${wx.env.USER_DATA_PATH}/KEY_${pname}.zip`;
        const ui8 = new Uint8Array([...long2Bytes(Date.now() + 600000, "little"), ...flags]);
        const sum = ui8.reduce((acc, cur) => acc + cur);
        ui8[ui8.length - 2] = (sum & 0xFFFF) >> 8;
        ui8[ui8.length - 1] = (sum & 0xFF);
        const token = Uint8Array2HexStr(ui8);

        const paramsUi8 = new Uint8Array([...Array.from(`${placeId}/${formData.lamps}/${formData.available}`).map(c => (c.charCodeAt())), ...flags]);
        const paramSum = paramsUi8.reduce((acc, cur) => acc + cur);
        paramsUi8[paramsUi8.length - 2] = (paramSum & 0xFFFF) >> 8;
        paramsUi8[paramsUi8.length - 1] = (paramSum & 0xFF);
        const params = Uint8Array2HexStr(paramsUi8);
        const url = `${httpBaseUrl}/szm/room/key/${params}/${token}/KEY_${pname}.zip`; // 下载url
        this.setData({downloadUrl: url});
        wx.showToast({
            title: '已生成密码',
        })
    },

    tapShare: function(){
        if (this.data.downloadUrl) {
            this.setData({showloading: true});
            const _this = this;
            wx.downloadFile({
                url: this.data.downloadUrl,
                filePath: tempFilePath,
                success(res) {
                    wx.shareFileMessage({
                        filePath: tempFilePath,
                        success() {},
                        fail: console.error,
                    })
                },
                complete(res) {
                    _this.setData({showloading: false});
                }
            })
        } else {
            wx.showToast({
              title: '未生成智控密码',
              icon: 'none'
            })
        }
    },

    tapCopy: function (params) {
        if (this.data.downloadUrl) {
            wx.setClipboardData({
                data: this.data.downloadUrl
            })
        } else {
            wx.showToast({
              title: '未生成智控密码',
              icon: 'none'
            })
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        const eventChannel = this.getOpenerEventChannel();
        eventChannel.on("rlist", res => {
            const list = res.filter(r => r.zkDeviceCode && r.zkLinkPwd);
            this.setData({rList: list})
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    tapAvailableCount: function(params) {
        this.setData({showActionsheet: !this.data.showActionsheet});
    },

    /**action sheet 回调 */
    tapSheetItem: function(e){
        setTimeout(() => {
            this.setData({showActionsheet: !1})
        }, 300);
        const {value} = e.detail
        const {groups} = this.data;
        groups.forEach(g => g.type = g.value === value ? 'warn' : '')
        this.setData({
            ['formData.available']: value,
            groups
        });
    },

    radioChange(e) {
        this.setData({
            ['formData.lamps']: e.detail.value,
        });
    },
})